package org.jeecg.modules.pucheng.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.BeanWrap;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.pucheng.entity.CombinedUser;
import org.jeecg.modules.pucheng.entity.Event;
import org.jeecg.modules.pucheng.entity.EventFile;
import org.jeecg.modules.pucheng.service.ICombinedUserService;
import org.jeecg.modules.pucheng.service.IEventFileService;
import org.jeecg.modules.pucheng.service.IEventService;
import org.jeecg.modules.pucheng.vo.EventVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/pucheng/heZhangApi")
@Api(tags = "河长制api")
public class HeZhangApiCtrl {
    private static String token = "";
    @Autowired
    private ICombinedUserService combinedUserService;
    @Autowired
    private IEventService eventService;
    @Autowired
    private IEventFileService eventFileService;
    @Autowired
    private HeZhangController heZhangController;

    private CombinedUser getCurrentUser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<CombinedUser> querySaWrapper = new LambdaQueryWrapper<CombinedUser>();
        querySaWrapper.eq(CombinedUser::getUserId, sysUser.getId());
        List<CombinedUser> users = combinedUserService.list(querySaWrapper);
        if (users.size() > 1) {
            throw new JeecgBootException("数据有误");
        } else if (users.size() == 0) {
            throw new JeecgBootException("账号未配置");
        }
        CombinedUser login = users.get(0);
        return login;
    }

    /**
     * 接口访问地址：
     *
     * @return
     */
    @ApiOperation(value = "获取token", notes = "获取token")
    @PostMapping(value = "/getToken")
    public Result<?> getToken() {
        //app_id：10011，app_secret：8617c6bde02f4a3182b8fd63871d4276
        String url = "http://npszhhz.cn/RiverChiefSystem/loginController/getToken.do";
        Map<String, Object> param = new HashMap<>();
        //{"appId":"78942","appSecret":"8617c6bde02f4a3182b8fd63871d4276"}
        param.put("appId", "10011");
        param.put("appSecret", "8617c6bde02f4a3182b8fd63871d4276");
        CombinedUser combinedUser = getCurrentUser();
        param.put("username", combinedUser.getUsername1());
        param.put("password", combinedUser.getPassword1());
        HttpResponse response = HttpRequest.post(url).header(Header.CONTENT_TYPE, "application/json;charset=UTF-8").body(JSONUtil.parseFromMap(param)).execute();
        String resultStr = response.body();
        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        token = jsonObject.getString("token");
        return Result.ok(token);
    }

    @ApiOperation(value = "获取所有事件", notes = "获取所有事件")
    @PostMapping(value = "/queryAllEvent")
    public Result<Object> queryAllEvent(int pageNo, int pageSize) {
        String url = "http://npszhhz.cn/RiverChiefSystem/eventController/queryAllEvent.do";
        //x-hzz-token
        Map<String, Object> param = new HashMap<>();
        param.put("pageNo", pageNo);
        param.put("pageSize", pageSize);
        Map<String, String> header = new HashMap<>();
        header.put("x-hzz-token", token);
        HttpResponse response = HttpRequest.post(url).header(Header.CONTENT_TYPE, "application/json;charset=UTF-8").addHeaders(header).body(JSONUtil.parseFromMap(param)).execute();
        String resultStr = response.body();
        JSONObject jsonObject = JSONObject.fromObject(resultStr);

        //"eventList":[{"eventId":0,"eventName":null,"eventCode":"20191113182013","eventLevel":null,"eventLevelName":"一般","patrolRecordId":0,"reportType":null,"reportTypeName":"河长督办","eventContent":"其他,","eventPoint":"[118.44987453,27.84187074];","address":"","eventType":null,"eventTypeName":"已完成","operaType":null,"operaTypeName":null,"riverId":null,"riverName":"浦城县临江镇瓦铺村三八垅","regionId":null,"regionName":"瓦铺村委会","problemType":null,"problemTypeName":"其他","eventTime":1573640413000,"updateTime":1573640433000,"limitTime":null,"userId":0,"realName":"陈文元","recordName":null,"eventStatus":0,"remark":"","patrolRecord":null,"patrolRange":null,"startTime":1573604252000,"endTime":1573606974000,"isAccountability":0,"nowRealName":null,"eventFileList":[{"eventFileId":201110,"eventId":0,"workflowLogId":0,"fileName":"2019111318201498.jpeg","fileUrl":"/event/beforeimg/Capture_2019-08-15_08-52_2715058501755030331020191113182014.jpeg","type":"image","status":0,"smallUrl":null,"imageTime":null,"submitTime":1573640416000,"remark":null}]}
        try {
            JSONArray array = jsonObject.getJSONArray("eventList");
            List<Object> objs = Arrays.asList(array.toArray());
            List<EventVo> events = new ArrayList<>();
            for (Object o : objs) {
                JSONObject jsonObject1 = (JSONObject) o;

                Map classMap = new HashMap();
                classMap.put("eventFileList", org.jeecg.modules.pucheng.vo.EventFile.class);
                EventVo eventVo = (EventVo) JSONObject.toBean(jsonObject1, EventVo.class, classMap);
                events.add(eventVo);
            }
            return Result.ok(events);
        } catch (JSONException e) {

        }
        return Result.error("请重新获取token");
    }

    //@ApiOperation(value="分步获取所有事件", notes="分步获取所有事件")
    @PostMapping(value = "/queryAllEventByStep")
    public Result<Object> queryAllEventByStep() {
        LambdaQueryWrapper<Event> querySaWrapper = new LambdaQueryWrapper<Event>();
        List<Event> all = eventService.list(querySaWrapper);
        List<String> ids = all.stream().map(Event::getId).collect(Collectors.toList());
        if (ids.size() > 0) {
            boolean rm = eventService.removeByIds(ids);
            if (!rm) {
                return Result.error("旧数据未成功清除");
            }
        }

        int pageNo = 0;
        for (int i = 0; i < 10000; i++) {
            pageNo++;

            //Result<Object> result = queryAllEvent(pageNo,10);
//            if (!RedisLock.tryLock("queryAllEventByStep")){
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(50000);
//                        } catch (InterruptedException e){
//
//                        }
//                    }
//                }).start();
//                continue;
//            }
            int back = 0;
            try {
                back = saveEvent(pageNo);
            } catch (Exception e) {
                heZhangController.loginSystem();
                back = saveEvent(pageNo);
            }
            if (back < 100) {
                //RedisLock.unLock("queryAllEventByStep");
                break;
            }
        }

        return Result.error("请重新获取token");
    }


    private synchronized int saveEvent(int pageNo) {
        Result result = heZhangController.queryEventByWeb(pageNo, 100,null,null,null,null,null,null,null,null);
        if (result.getCode() == 200) {
            JSONObject jsonObject = JSONObject.fromObject(result.getResult());
            JSONArray array = jsonObject.getJSONArray("records");
            List<Object> objs = Arrays.asList(array.toArray());
            List<EventVo> events = new ArrayList<>();
            for (Object o : objs) {
                JSONObject jsonObject1 = (JSONObject) o;
                EventVo eventVo = (EventVo) JSONObject.toBean(jsonObject1, EventVo.class);
                events.add(eventVo);
                Event event = new Event();
                BeanUtil.copyProperties(eventVo, event);
                event.setId(UUIDGenerator.generate());
                eventService.save(event);
                List<org.jeecg.modules.pucheng.vo.EventFile> eventFiles = eventVo.getEventFileList();
                if (eventFiles != null) {
                    List<EventFile> saveFiles = new ArrayList<>();
                    BeanWrap.copyList(eventFiles, saveFiles, EventFile.class);
                    for (EventFile file : saveFiles) {
                        file.setId(UUIDGenerator.generate());
                    }
                    eventFileService.saveBatch(saveFiles);
                }
            }
            return events.size();
        } else {
            throw new JeecgBootException("获取失败");
        }
    }

    //http://npszhhz.cn/RiverChiefSystem/eventController/queryDetailByEventCode.do
    @ApiOperation(value = "获取最新事件", notes = "获取最新事件")
    @PostMapping(value = "/queryNewEvent")
    public Result<Object> queryNewEvent() {
        Result result = heZhangController.queryEventByWeb(1, 200,null,null,null,null,null,null,null,null);
        if (result.getCode() == 200) {
            JSONObject jsonObject = JSONObject.fromObject(result.getResult());
            JSONArray array = jsonObject.getJSONArray("records");
            List<Object> objs = Arrays.asList(array.toArray());
            for (Object o : objs) {
                JSONObject jsonObject1 = (JSONObject) o;
                EventVo eventVo = (EventVo) JSONObject.toBean(jsonObject1, EventVo.class);
                Event event = new Event();
                BeanUtil.copyProperties(eventVo, event);
                LambdaQueryWrapper<Event> querySaWrapper = new LambdaQueryWrapper<Event>();
                querySaWrapper.eq(Event::getEventCode, event.getEventCode());
                List<Event> all = eventService.list(querySaWrapper);
                if (all.size() != 0) {
                    continue;
                }
                event.setId(UUIDGenerator.generate());
                eventService.save(event);
                List<org.jeecg.modules.pucheng.vo.EventFile> eventFiles = eventVo.getEventFileList();
                if (eventFiles != null) {
                    List<EventFile> saveFiles = new ArrayList<>();
                    BeanWrap.copyList(eventFiles, saveFiles, EventFile.class);
                    for (EventFile file : saveFiles) {
                        file.setId(UUIDGenerator.generate());
                    }
                    eventFileService.saveBatch(saveFiles);
                }
            }
            return Result.ok();
        }
        return Result.error("获取失败");
    }

}
